package com.basic.business.common.redis;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.Set;

/**
 * spring redis 工具类
 *
 * @author zhaoxy_jn@163.com
 **/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCacheUtils
{
    @Resource
    public RedisTemplate redisTemplate;

    public static RedisTemplate staticRedisTemplate;

    // 项目启动时把redisTemplate交给静态的staticRedisTemplate
    @PostConstruct
    public void init() {
        staticRedisTemplate = this.redisTemplate;
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public static <T> void setCacheObject(final String key, final T value)
    {
        staticRedisTemplate.opsForValue().set(key, value);
    }

    /**
     * 判断 key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public static Boolean hasKey(String key)
    {
        return staticRedisTemplate.hasKey(key);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public static <T> T getCacheObject(final String key)
    {
        ValueOperations<String, T> operation = staticRedisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public static boolean deleteObject(final String key)
    {
        return staticRedisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public static boolean deleteObject(final Collection collection)
    {
        return staticRedisTemplate.delete(collection) > 0;
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public static Set<String> keys(final String pattern)
    {
        return staticRedisTemplate.keys(pattern);
    }

    /**
     * 重命名key
     * @param oldKey 旧key
     * @param newKey 新key
     */
    public static void rename(String oldKey, String newKey) {
    	staticRedisTemplate.rename(oldKey, newKey);
    }

    public static void updateSet(String key, String oldValue, String newValue){
        SetOperations<String, String> setOps = staticRedisTemplate.opsForSet();

        // 删除旧元素
        setOps.remove(key, oldValue);

        // 添加新元素
        setOps.add(key, newValue);
    }

    /**
     * 清空指定key的缓存
     */
    public static void clearCache(String key) {
        Collection<String> keys = keys(key);
        if (!keys.isEmpty()) {
            deleteObject(keys);
        }
    }

}
